package com.zpb.admin.filter;

import com.alibaba.fastjson.JSON;
import com.zpb.framework.domain.ApiResult;
import com.zpb.framework.domain.entity.UserInfo;
import com.zpb.framework.domain.enums.ResultCodeEnum;
import com.zpb.framework.utils.JwtUtil;
import com.zpb.framework.utils.RedisCache;
import com.zpb.framework.utils.ServletUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.Objects;

/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2025/9/11
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        log.info("===== JwtAuthenticationTokenFilter 开始执行 =====");
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        token = token.substring(7);

        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            String result = JSON.toJSONString(ApiResult.error(ResultCodeEnum.USER_NO_LOGIN.getCode(), "用户未登录"));
            ServletUtil.renderString(response,result);
            return;
        }
        String redisUserId = "adminLogin:" + userId;
        UserInfo userInfo = redisCache.getCacheObject(redisUserId);
        if (Objects.isNull(userInfo)) {
            String result = JSON.toJSONString(ApiResult.error(ResultCodeEnum.USER_NO_LOGIN.getCode(), "用户未登录"));
            ServletUtil.renderString(response,result);
            return;
        }
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) userInfo.getAuthorities();
        if (authorities == null || authorities.isEmpty()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userInfo, null,authorities );
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

//        System.out.println("JWT过滤器后：" + SecurityContextHolder.getContext().getAuthentication());
//        System.out.println("是否认证：" + SecurityContextHolder.getContext().getAuthentication().isAuthenticated());
//        System.out.println("权限：" + SecurityContextHolder.getContext().getAuthentication().getAuthorities());

        filterChain.doFilter(request, response);
    }
}
